package com.guosen.zebra.framework.starter.sso.service.impl;

import com.guosen.zebra.framework.starter.sso.constant.SsoConstant;
import com.guosen.zebra.framework.starter.sso.properties.SsoProperties;
import com.guosen.zebra.framework.starter.sso.service.SsoSupportService;
import com.guosen.zebra.framework.starter.sso.vo.SsoLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.function.ServerRequest;

@Slf4j
public class SsoSupportServiceImpl implements SsoSupportService {

    private final SsoProperties ssoProperties;

    public SsoSupportServiceImpl(SsoProperties ssoProperties) {
        this.ssoProperties = ssoProperties;
    }

    @Override
    public String redirectPage(String returnUrl) {
        String homePage = ssoProperties.getHomePage();
        if (StringUtils.isNotEmpty(returnUrl)) {
            return SsoConstant.REDIRECT_PREFIX + returnUrl;
        }
        if (StringUtils.isNotBlank(homePage)) {
            return SsoConstant.REDIRECT_PREFIX + homePage;
        }
        // 如果没有配置首页，则提示登录成功
        return loginSuccessPage();
    }

    @Override
    public String autoPostLoginPage(SsoLoginVO ssoLoginVO, ServerRequest request) {
        request.attributes().put("ssoLogin", ssoLoginVO);
        return addTemplatesPath(SsoConstant.AUTO_POST_LOGIN_TEMPLATE);
    }

    @Override
    public String loginSuccessPage() {
        return addTemplatesPath(SsoConstant.SUCCESS_TEMPLATE);
    }

    @Override
    public String errorPage(String errorMsg, ServerRequest request) {
        request.attributes().put("errorMessage", errorMsg);
        return addTemplatesPath(SsoConstant.ERROR_TEMPLATE);
    }

    private String addTemplatesPath(String view) {
        return ssoProperties.getTemplatesPath() + "/" + view;
    }
}
